package com.gupao.vip.bio;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 创建服务器
 * 写出数据：输出流
 * 读取数据：输入流
 * @author dell
 *
 */
public class Server {
	private List<UserChannel> userChannels = new ArrayList<UserChannel>();
	
	public static void main(String[] args) {
		try {
			new Server().start();
		} catch (IOException e) {
			System.err.println(e);
		}
	}
	
	public void start() throws IOException{
		ServerSocket serverSocket = new ServerSocket(Constants.DEFAULT_PORT);
		System.out.println("已经启动服务器了，可以收发消息了");
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		while(true){
			Socket client = serverSocket.accept();
			UserChannel channel = new UserChannel(client);
			channel.init();
			userChannels.add(channel);
			executorService.execute(channel);
		}
	}
	/**
	 * 一个客户端 一条道路
	 * @author dell
	 *
	 */
	private class UserChannel implements Runnable{
		private DataInputStream dataInputStream = null;
		
		private DataOutputStream dataOutputStream = null;
		
		private boolean isRunning = true;
		
		private String name;
		
		private Socket client;
		
		public UserChannel(Socket client){
			this.client = client;
		}
		
		private void init(){
			try {
				dataInputStream = new DataInputStream(client.getInputStream());
				dataOutputStream = new DataOutputStream(client.getOutputStream());
				this.name = dataInputStream.readUTF();
				this.send("欢迎您进入聊天室");
				this.sendOther(this.name + "进入了聊天室", true);
			} catch (IOException e) {
				System.err.println(e);
				IOUtils.closeQuietly(dataInputStream);
				IOUtils.closeQuietly(dataOutputStream);
				isRunning = false;
			}
			
		}
		@Override
		public void run() {
			while(isRunning){
				sendOther(receive(), false);
			}
			
		}
		
		/**
		 * 读取数据
		 * @return
		 */
		private String receive(){
			String msg = "";
			try {
				msg = dataInputStream.readUTF();
			} catch (IOException e) {
				System.err.println(e);
				IOUtils.closeQuietly(dataInputStream);
				isRunning = false;
				userChannels.remove(this);
			}
			return msg;
		}
		
		/**
		 * 发送数据
		 * @param msg
		 */
		private void send(String msg){
			if(StringUtils.isEmpty(msg)){
				return;
			}
			try {
				dataOutputStream.writeUTF(msg);
				dataOutputStream.flush();
			} catch (IOException e) {
				System.err.println(e);
				IOUtils.closeQuietly(dataOutputStream);
				isRunning = false;
				userChannels.remove(this);
			}
		}
		
		/**
		 * 发送给其他客户端
		 * @param msg
		 * @param sys
		 */
		private void sendOther(String msg, boolean sys){
			if(StringUtils.startsWith(msg, "@") && StringUtils.indexOf(msg, ":") > -1){
				//私聊
				String name = StringUtils.substring(msg, 1, StringUtils.indexOf(msg, ":"));
				String content = StringUtils.substringAfter(msg, ":");
				for(UserChannel channel : userChannels){
					if(name.equals(channel.name)){
						channel.send(this.name + "对您悄悄地说：" + content);
					}
				}
			}else{
				//群聊
				for(UserChannel channel : userChannels){
					if(this == channel){
						continue;
					}
					if(sys){
						//系统消息
						channel.send("系统消息：" + msg);
					}else{
						//发送给其他的客户端
						channel.send(this.name + "对所有人说：" + msg);
					}
				}
			}
		}
	}
}
